package map;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/*统计字符串每个字符的个数*/
public class TestDemo {
    public static void main(String[] args) {
        System.out.println("输入字符串");
        Scanner input = new Scanner(System.in);
        String string = input.nextLine();
        findChar1(string);
        findChar2(string);
    }

    private static void findChar1(String string) {
        //String ——>字符数组 :toCharArray()
        char[] chars = string.toCharArray();
        HashMap<Character, Integer> hs = new HashMap<>();
        for (Character c : chars) {
            if (hs.containsKey(c)) {
                hs.put(c, hs.get(c) + 1);
            } else {
                hs.put(c, 1);
            }
        }
        for (Map.Entry<Character, Integer> entry : hs.entrySet()
        ) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }
    }

    private static void findChar2(String string) {
        // 1:创建⼀个集合 存储字符 以及其出现的次数
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        // 2:遍历字符串
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            // 判断 该字符是否在键集中
            if (!map.containsKey(c)) {// 说明这个字符没有出现过
                // 那就是第⼀次
                map.put(c, 1);
            } else {
                map.put(c, map.get(c) + 1);
            }
        }
    }
}
